package mysql

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"jingdong-product/appconfig"
)

var DB *gorm.DB
var err error

func Init() {
	mys := appconfig.AppConf.MysqlConfig
	// 参考 https://github.com/go-sql-driver/mysql#dsn-data-source-name 获取详情
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		mys.User, mys.Password, mys.Host, mys.Post, mys.DataBase)
	DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		println("数据库链接失败")
	}
	fmt.Println("数据库链接成功")
	err = DB.AutoMigrate(&User{}, &Product{})
	if err != nil {
		println("数据库迁移失败")
	}
	fmt.Println("数据库迁移成功")
}
